package cn.lklink.pay.lkl.core;

import cn.lklink.pay.lkl.request.LakalaRequest;
import cn.lklink.pay.lkl.util.HttpUtil;
import com.google.gson.Gson;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;

import java.io.IOException;

/**
 * 拉卡拉支付sdk客户端
 *
 * @author Mr丶xie
 * @version 1.0.0
 * @mail xielinke@lklink.cn
 */
public class LakalaPayClient {

    /**
     * 拉卡拉支付客户端执行操作
     *
     * @param url           请求地址
     * @param lakalaRequest 请求参数
     * @return 响应报文
     */
    public static String execute(String url, LakalaRequest lakalaRequest) throws IOException {
        String body = new Gson().toJson(lakalaRequest);
        String authorization = LakalaPayKit.getAuthorization(body);
        return execute(url, body, "LKLAPI-SHA256withRSA " + authorization);
    }

    public static String execute(String url, String body, String authorization) throws IOException {
        HttpResponse response = HttpUtil.post(url, body, authorization);
        if (response.getStatusLine().getStatusCode() != 200) {
            return "";
        }

        String appid = HttpUtil.getHeadValue(response, "Lklapi-Appid");
        String lklapiSerial = HttpUtil.getHeadValue(response, "Lklapi-Serial");
        String timestamp = HttpUtil.getHeadValue(response, "Lklapi-Timestamp");
        String nonce = HttpUtil.getHeadValue(response, "Lklapi-Nonce");
        String signature = HttpUtil.getHeadValue(response, "Lklapi-Signature");

        String resp = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        String source = appid + "\n" + lklapiSerial + "\n" + timestamp + "\n" + nonce + "\n" + resp + "\n";
        boolean verify = LakalaPayKit.verify(source.getBytes("UTF-8"), signature);
        if (!verify) {
            return "";
        }
        return resp;
    }


}
